package com.ysd.shiro;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.ysd.entity.Permission;
import com.ysd.entity.UserInfo;
import com.ysd.entity.roles;
import com.ysd.Service.UserInfoService;

public class CustomRealm extends AuthorizingRealm {
 
	@Autowired
	private UserInfoService userInfoService;
	
	/**
	 *  授权（赋予权限）
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		System.out.println("授权");
		
		
		//通过principals获取操作的主体
		UserInfo user = (UserInfo) principals.getPrimaryPrincipal();
		
		//让shiro知道主体拥有哪些权限
		SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
		 
		for(roles role : user.getRoleList()) {
			System.out.println(role.getRname());
			//告诉shiro这个用户拥有哪些角色
			simpleAuthorizationInfo.addRole(role.getRname());
			for(Permission permission : role.getpList()) { 
				System.out.println(permission.getPname());
				//告诉shiro这个用户拥有哪些权限
				simpleAuthorizationInfo.addStringPermission(permission.getPname());
			}
		}
		return simpleAuthorizationInfo;
	}

	/**
	 * 认证（登录）
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) 
			throws AuthenticationException {
		System.out.println("认证");
		
		//获取当前操作主体subject的用户名
		String uname = (String) authenticationToken.getPrincipal();
		
		UserInfo user = userInfoService.findByUname(uname);
		
		//判断用户是否存在
		if(user == null) {
			return null;
		}else {
			//判断密码是否正确
			
			/*
			 * 1、操作的主体，或传操作主体的用户名
			 * 2、主体密码
			 * 3、当前realm对象
			 */
			SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(
					user, user.getPasscheck(), getName());
			
			return simpleAuthenticationInfo;
		}
	}

}
